package com.zhb.core.shiro.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.zhb.sys.shiro.model.Function;
import com.zhb.sys.shiro.model.Role;
import com.zhb.sys.shiro.model.User;
import com.zhb.sys.shiro.user.service.UserService;


public class MonitorRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;

	// 做授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 查询当前用户具有 角色和权限
		String userName = (String) super.getAvailablePrincipal(principals);
		User user = userService.selectUserRoleAndFunctionByUserName(userName);
		List<Role> roleList = user.getRoleList();
		for (Role role : roleList) {
			// 将role加入返回授权的Info
			List<Function> functionList = role.getFunctionList();
			for (Function function : functionList) {
				authorizationInfo.addStringPermission(function.getFunctionCode());
			}
			authorizationInfo.addRole(role.getRoleCode());
		}
		return authorizationInfo;
	}
	// 做认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authenticationToken)
			throws AuthenticationException {
		// 获得存放用户名和密码的令牌
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		String password = userService.selectPasswordByUserName(token
				.getUsername());
		if (password == null) {
			// 没有用户名
			return null; // 用户名不存在异常
		} else {
			return new SimpleAuthenticationInfo(token.getUsername(),
					password.toCharArray(), getName());
		}
	}
}
